package com.soriya.nestlive.screen.live

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Button
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.outlined.ModeEdit
import androidx.compose.material.rememberBottomSheetState
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.net.toFile
import androidx.hilt.navigation.compose.hiltViewModel
import com.soriya.nestlive.component.CustomEditText
import com.soriya.nestlive.component.CustomImage
import com.soriya.nestlive.component.MediumText
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.component.SmallAdditionalText
import com.soriya.nestlive.component.SmallText
import com.soriya.nestlive.component.SmallTitle
import com.soriya.nestlive.component.SmallerText
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.model.Category
import com.soriya.nestlive.model.form.PublishVideoForm
import com.soriya.nestlive.util.ToastUtil
import com.soriya.nestlive.viewmodel.VideoModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.ByteArrayOutputStream
import java.io.File

@OptIn(ExperimentalMaterialApi::class, ExperimentalLayoutApi::class)
@Composable
fun PublishVideoScreen(
    toBack: () -> Unit
) {

    val context = LocalContext.current

    val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val coroutineScope = rememberCoroutineScope()

    val videoModel: VideoModel = hiltViewModel()

    var title by remember {
        mutableStateOf("")
    }

    var desc by remember {
        mutableStateOf("")
    }

    var sourceFile: File? = null

    var cover: ByteArray? = null

    var coverBitmap by remember {
        mutableStateOf<Bitmap?>(null)
    }

    var category by remember {
        mutableStateOf<Category?>(null)
    }

    val tags = remember {
        mutableStateListOf<String>()
    }

    var duration: Long = 0

    var modalType by remember {
        mutableStateOf(-1)
    }

    val videoLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { uri ->
            if (uri == null) {
                toBack()
                ToastUtil.show(context = context, "未选择视频")
                return@rememberLauncherForActivityResult
            }

            val documentId = DocumentsContract.getDocumentId(uri)

            when (uri.authority) {
                "com.android.providers.media.documents" -> {
                    // 媒体
                    val cursor = context.contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, "_id=?", arrayOf(documentId.split(":")[1]), null)
                    cursor?.let {
                        it.moveToNext()
                        val columnIndex = it.getColumnIndex(MediaStore.Images.Media.DATA)
                        val path = it.getString(columnIndex)
                        sourceFile = File(path)
                        it.close()
                    }
                }
                "com.android.externalstorage.documents" -> {
                    // 文件
                    val type = documentId.split(":")[0]
                    if ("primary" == type) {
                        sourceFile = File(Environment.getExternalStorageDirectory().path + "/" + documentId.split(":")[1])
                    }
                }
            }

            val mediaMetadataRetriever = MediaMetadataRetriever()
            mediaMetadataRetriever.setDataSource(context, uri)
            coverBitmap = mediaMetadataRetriever.getFrameAtTime(
                100000,
                MediaMetadataRetriever.OPTION_CLOSEST
            )

            if (coverBitmap != null) {
                val outputStream = ByteArrayOutputStream()
                coverBitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                cover = outputStream.toByteArray()
            }

            duration =
                mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong()
                    ?.div(1000) ?: 0
        }
    )

    val coverLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { uri ->
            if (uri != null) {
                val openInputStream = context.contentResolver.openInputStream(uri)
                coverBitmap = BitmapFactory.decodeStream(openInputStream)
                if (coverBitmap != null) {
                    val outputStream = ByteArrayOutputStream()
                    coverBitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                    cover = outputStream.toByteArray()
                }
                coroutineScope.launch(Dispatchers.IO) {
                    openInputStream?.close()
                }
            }
        }
    )

    LaunchedEffect(Unit) {
        videoLauncher.launch("video/*")
    }


    ModalBottomSheetLayout(
        sheetContent = {
            // 底部动作条
            when (modalType) {
                0 -> {
                    CategoryModal(
                        onSelected = {
                            category = it
                            coroutineScope.launch {
                                sheetState.hide()
                            }
                        }
                    )
                }
                1 -> {
                    TagModal(
                        onComplete = {
                            tags += it
                            coroutineScope.launch {
                                sheetState.hide()
                            }
                        }
                    )
                }
            }
        },
        sheetState = sheetState,
        sheetBackgroundColor = MaterialTheme.colors.background
    ) {
        ScreenColumnContent(
            modifier = Modifier.padding(vertical = UIValue.VERTICAL_PADDING)
        ) {
            Column(
                modifier = Modifier.weight(1F)
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(150.dp, 100.dp)
                            .clickable {
                                coverLauncher.launch("image/*")
                            }
                    ) {
                        if (coverBitmap != null) {
                            Image(
                                bitmap = coverBitmap!!.asImageBitmap(),
                                contentDescription = "Preview",
                                contentScale = ContentScale.Crop,
                                modifier = Modifier
                                    .fillMaxSize()
                                    .clip(RoundedCornerShape(UIValue.SMALLER_RADIUS))
                            )
                        }
//                        CustomImage(
//                            url = "https://img2.baidu.com/it/u=3994669564,1460731068&fm=253&fmt=auto&app=138&f=JPEG?w=835&h=500",
//                            contentDescription = "Preview",
//                            shape = RoundedCornerShape(UIValue.SMALLER_RADIUS),
//                            modifier = Modifier
//                                .fillMaxSize()
//                        )

                        Row(
                            horizontalArrangement = Arrangement.Center,
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .align(Alignment.BottomCenter)
                                .fillMaxWidth()
                                .height(30.dp)
                                .clip(
                                    RoundedCornerShape(
                                        0.dp,
                                        0.dp,
                                        UIValue.SMALLER_RADIUS,
                                        UIValue.SMALLER_RADIUS
                                    )
                                )
                                .background(Color.Black.copy(0.5F))
                        ) {
                            CompositionLocalProvider(LocalContentColor provides Color.White) {
                                Icon(
                                    imageVector = Icons.Outlined.ModeEdit,
                                    contentDescription = "Edit Cover",
                                    modifier = Modifier.size(14.dp)
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                SmallText(text = "修改封面")
                            }
                        }
                    }

                    BasicTextField(
                        value = title,
                        onValueChange = { title = it },
                        decorationBox = { innerTextField ->
                            Box(
                                modifier = Modifier.fillMaxSize()
                            ) {
                                if (title.isEmpty()) SmallText(text = "合适的标题可以吸引更多人观看~", color = MaterialTheme.colors.surface)
                                innerTextField()

                                SmallText(
                                    text = "${title.length}/30",
                                    modifier = Modifier.align(Alignment.BottomEnd)
                                )
                            }
                        },
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(
                                horizontal = UIValue.HORIZONTAL_PADDING
                            )
                    )
                }

                Spacer(
                    modifier = Modifier
                        .padding(vertical = 20.dp)
                        .fillMaxWidth()
                        .height(1.dp)
                        .background(Color.Black)
                )

                Title(text = "分类") {
                    Row(
                        modifier = Modifier.clickable {
                            coroutineScope.launch {
                                modalType = 0
                                sheetState.show()
                            }
                        }
                    ) {
                        CompositionLocalProvider(LocalContentColor provides MaterialTheme.colors.primary) {
                            SmallTitle(text = "选择分类")
                            Icon(imageVector = Icons.Default.Add, contentDescription = "Select Category")
                        }
                    }
                }

                if (category != null) FlowRow(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    TagItem(modifier = Modifier.padding(end = 6.dp), tag = category!!.categoryName, key = 0)
                } else Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(36.dp)
                ) {
                    SmallAdditionalText(text = "无分类")
                }

                Title(text = "标签") {
                    Row(
                        modifier = Modifier.clickable {
                            coroutineScope.launch {
                                modalType = 1
                                sheetState.show()
                            }
                        }
                    ) {
                        CompositionLocalProvider(LocalContentColor provides MaterialTheme.colors.primary) {
                            SmallTitle(text = "添加标签")
                            Icon(imageVector = Icons.Default.Add, contentDescription = "Add Tags")
                        }
                    }
                }

                if (tags.size > 0) FlowRow(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    tags.forEachIndexed { index, item ->
                        TagItem(modifier = Modifier.padding(end = 6.dp), tag = item, key = index) {
                            if (it != null) {
                                tags.removeAt(it)
                            }
                        }
                    }
                } else Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(36.dp)
                ) {
                    SmallAdditionalText(text = "无标签")
                }

                Title(text = "描述")
                CustomEditText(
                    value = desc,
                    onValueChange = { desc = it },
                    shape = RoundedCornerShape(UIValue.SMALLER_RADIUS)
                )
            }


            Button(
                onClick = {
                    val publishVideoForm = PublishVideoForm(
                        channelId = 0L,
                        categoryId = category?.id ?: 0,
                        videoName = title,
                        videoDesc = desc,
                        source = sourceFile!!,
                        cover = cover!!,
                        duration = duration,
                        tags = tags.joinToString("|")
                    )
//                    Log.i("SoRiya", "publishVideoForm: $publishVideoForm")

                    coroutineScope.launch {
                        videoModel.publishVideo(publishVideoForm = publishVideoForm).collect {
                            ToastUtil.show(context, "上传成功，请等待转码")
                            toBack()
                        }
                    }
                },
                shape = RoundedCornerShape(50),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
            ) {
                MediumText(text = "发布")
            }
        }
    }
}